%%%-------------------------------------------------------------------
%%% @author Rain
%%% @doc 登录相关处理器
%%% @end
%%%-------------------------------------------------------------------
-module(login_phandler).
-author("Rain").
-include("role.hrl").
-include("common.hrl").
-include("login_pb.hrl").

%% API
-export([handle_c2s_msg/2]).


%% @doc 处理c2s消息
handle_c2s_msg(#login_auth_c2s{uid = Uid, uname = UName}, RoleState) ->
    ?LOG_INFO("Uid ~p UName ~p", [Uid, UName]),
    RoleList = get_role_list(),
    PRoleList = [#p_login_info{id = RoleId, name = Name} || {RoleId, Name} <- RoleList],
    ?R2C_MSG(#login_auth_s2c{role_list = PRoleList}),
    {noreply, RoleState};

handle_c2s_msg(#login_choose_role_c2s{role_id = RoleId}, RoleState) ->
    role_mgr_svr:update_role_info(RoleId),
    ?LOG_INFO("RoleId ~p Enter Game", [RoleId]),
    ?R2C_MSG(#login_choose_role_s2c{role_id = RoleId}),
    {noreply, RoleState#role_state{role_id = RoleId}};


handle_c2s_msg(Msg, #role_state{} = RoleState) ->
    ?LOG_ERROR("unhandler c2s msg  ~p", [Msg]),
    {noreply, RoleState}.


%% @doc 随机名字
random_name() ->
    [game_util_rand:rand($a, $z) || _ <- lists:duplicate(10, 0)].


%% @doc 随机角色id
random_role_id() ->
    list_to_integer([game_util_rand:rand($1, $9)|| _ <-lists:duplicate(10, 0)]).

%% @doc 自动创建角色
auto_create_role() ->
    RandomName = random_name(),
    RoleId = random_role_id(),
    [{RoleId, RandomName}].


get_role_list() ->
    case get(role_list) of
        undefined ->
            auto_create_role();
        Any ->
            Any
    end.





